package com.joyd.autobot

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlin.math.max
import java.lang.ref.WeakReference
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean

class WebSocketForegroundService : Service() {
    companion object {
        const val TAG = "WebSocketForegroundService"
        private const val CHANNEL_ID = "WebSocketServiceChannel"
        private const val NOTIFICATION_ID = 1001
        private const val ACTION_START = "com.joyd.autobot.action.START"
        private const val ACTION_STOP = "com.joyd.autobot.action.STOP"
        private const val IMAGE_READER_FORMAT = android.graphics.PixelFormat.RGBA_8888
        private const val IMAGE_READER_MAX_IMAGES = 2
        private const val VIRTUAL_DISPLAY_FLAGS = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR
        
        // 用于存储服务启动回调的静态变量
        private var serviceReadyCallback: ServiceReadyCallback? = null
        
        // 服务实例引用
        private var instance: WeakReference<WebSocketForegroundService>? = null
        
        // 清理服务实例引用的方法
        fun clearInstance() {
            instance?.clear()
            instance = null
        }
        
        // 静态方法：设置MediaProjection实例
        fun setMediaProjection(context: Context, resultCode: Int, resultData: Intent) {
            val service = instance?.get()
            if (service != null) {
                service.setMediaProjection(resultCode, resultData)
                // 立即尝试截图
                service.requestScreenshot()
            } else {
                // 如果服务未启动，先启动服务
                startServiceForMediaProjection(context, object : ServiceReadyCallback {
                    override fun onServiceReady() {
                        // 服务启动后再设置MediaProjection
                        val runningService = instance?.get()
                        runningService?.setMediaProjection(resultCode, resultData)
                        runningService?.requestScreenshot()
                    }
                })
            }
        }
        
        // 静态方法：检查是否有可用的MediaProjection实例并请求截图
        fun hasActiveMediaProjection(): Boolean {
            val service = instance?.get()
            return service?.mediaProjection != null
        }
        
        // 静态方法：获取服务实例
        fun getInstance(): WebSocketForegroundService? {
            return instance?.get()
        }
        
        // 静态方法：启动服务
        fun startService(context: Context) {
            val intent = Intent(context, WebSocketForegroundService::class.java)
            intent.action = ACTION_START
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        // 静态方法：为MediaProjection启动服务
        fun startServiceForMediaProjection(context: Context, callback: ServiceReadyCallback?) {
            serviceReadyCallback = callback
            val intent = Intent(context, WebSocketForegroundService::class.java)
            intent.action = ACTION_START
            intent.putExtra("TYPE", "MEDIA_PROJECTION")
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        // 静态方法：停止服务
        fun stopService(context: Context) {
            val intent = Intent(context, WebSocketForegroundService::class.java)
            intent.action = ACTION_STOP
            context.stopService(intent)
        }
        
        // 服务准备就绪回调接口
        interface ServiceReadyCallback {
            fun onServiceReady()
        }
        
        // 截图回调接口
        interface ScreenshotCallback {
            fun onScreenshotResult(success: Boolean, bitmap: Bitmap?)
        }
    }

    // 管理MediaProjection实例
    private var mediaProjection: MediaProjection? = null
    // 保存用户授权时的Intent，用于自动重建MediaProjection
    private var savedResultData: Intent? = null
    // 保存请求代码
    private var savedRequestCode: Int = 0
    // 标记是否正在尝试重建MediaProjection
    private var isRecreatingMediaProjection = false
    
    // 截图相关变量
    private var imageReader: ImageReader? = null
    private var virtualDisplay: VirtualDisplay? = null
    private val isScreenshotInProgress = AtomicBoolean(false)
    private val screenshotCallbacks = mutableListOf<ScreenshotCallback>()
    
    // WebSocket客户端
    // 注意：这里暂时使用Any类型，因为无法确定WebSocketClient的具体类型
    private var webSocketClient: Any? = null

    override fun onCreate() {
        super.onCreate()
        // 保存服务实例引用
        instance = WeakReference(this)
        
        // 创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "WebSocket Service",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            channel.description = "保持应用在后台运行以支持截图功能"
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
        
        // 创建并显示前台服务通知
        val notification = createNotification()
        startForeground(NOTIFICATION_ID, notification)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {
            when (intent.action) {
                ACTION_START -> {
                    // 处理服务启动
                    Log.d(TAG, "Service started")
                    
                    // 如果是为MediaProjection启动的服务，回调通知
                    if (intent.getStringExtra("TYPE") == "MEDIA_PROJECTION") {
                        val callback = serviceReadyCallback
                        serviceReadyCallback = null
                        callback?.onServiceReady()
                    }
                }
                ACTION_STOP -> {
                    // 处理服务停止
                    Log.d(TAG, "Service stopping")
                    stopForeground(true)
                    stopSelf()
                }
            }
        }
        
        // 如果被杀死，不需要重启
        return START_NOT_STICKY
    }

    // 创建前台服务通知
    private fun createNotification(): Notification {
        val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("AutoBot Service")
            .setContentText("Running in background")
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        
        return notificationBuilder.build()
    }

    // 实例方法：设置MediaProjection实例
    private fun setMediaProjection(resultCode: Int, resultData: Intent) {
        // 保存授权数据，用于后续重建MediaProjection
        savedResultData = resultData
        savedRequestCode = resultCode
        
        // 释放旧的MediaProjection资源
        releaseMediaProjection()
        
        // 创建新的MediaProjection实例
        val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData)
        
        // 设置MediaProjection停止监听
        mediaProjection?.registerCallback(object : MediaProjection.Callback() {
            override fun onStop() {
                super.onStop()
                Log.d(TAG, "MediaProjection stopped")
                mediaProjection = null
                virtualDisplay = null
                // 尝试自动重建MediaProjection
                scheduleMediaProjectionRecreation()
            }
        }, Handler(Looper.getMainLooper()))
    }

    /**
     * 安排MediaProjection重建
     */
    private fun scheduleMediaProjectionRecreation() {
        // 避免重复重建
        if (isRecreatingMediaProjection) {
            return
        }
        
        isRecreatingMediaProjection = true
        Handler(Looper.getMainLooper()).postDelayed({
            try {
                recreateMediaProjection()
            } catch (e: Exception) {
                Log.e(TAG, "Failed to recreate MediaProjection: ", e)
            } finally {
                isRecreatingMediaProjection = false
            }
        }, 1000) // 延迟1秒后尝试重建
    }

    /**
     * 重建MediaProjection实例
     */
    private fun recreateMediaProjection() {
        if (savedResultData != null) {
            Log.d(TAG, "Attempting to recreate MediaProjection")
            setMediaProjection(savedRequestCode, savedResultData!!)
        } else {
            Log.w(TAG, "No saved MediaProjection data available for recreation")
            // 通知UI层需要重新请求权限
            notifyPermissionRequired()
        }
    }

    /**
     * 通知UI层需要重新请求权限
     */
    private fun notifyPermissionRequired() {
        Log.d(TAG, "MediaProjection permission required, sending broadcast to UI")
        val intent = Intent("com.joyd.autobot.MEDIA_PROJECTION_PERMISSION_REQUIRED")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.setPackage(packageName) // 指定包名，解决UnsafeImplicitIntentLaunch错误
        sendBroadcast(intent)
    }

    /**
     * 安全地检查和访问系统资源
     */
    private fun checkSystemResourceAccess(resourceType: String): Boolean {
        try {
            // 这里可以根据需要添加特定资源的检查逻辑
            return true
        } catch (e: SecurityException) {
            Log.w(TAG, "没有权限访问${resourceType}资源: ${e.message}")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "检查${resourceType}资源时出错: ${e.message}", e)
            return false
        }
    }

    /**
     * 在takeScreenshot方法前添加安全检查
     */
    fun requestScreenshotSafely() {
        Log.d(TAG, "requestScreenshotSafely: 安全请求截图开始")
        
        // 检查MediaProjection状态
        if (mediaProjection == null) {
            Log.w(TAG, "requestScreenshotSafely: MediaProjection实例为空，需要先请求权限")
            // 尝试重建MediaProjection
            recreateMediaProjection()
            // 通知UI层需要权限
            notifyPermissionRequired()
            return
        }
        
        // 检查服务状态
        if (!isServiceRunning) {
            Log.w(TAG, "requestScreenshotSafely: 服务未正常运行，当前服务状态: ${instance?.get()}, mediaProjection: $mediaProjection")
            return
        }
        
        if (checkSystemResourceAccess("MediaProjection")) {
            Log.d(TAG, "requestScreenshotSafely: 安全检查通过，执行截图")
            // 将请求加入队列，避免阻塞主线程
            Handler(Looper.getMainLooper()).post {
                if (isScreenshotInProgress.get()) {
                    Log.d(TAG, "requestScreenshotSafely: 已有截图操作在进行中，将请求添加到队列")
                    screenshotCallbacks.add(object : ScreenshotCallback {
                        override fun onScreenshotResult(success: Boolean, bitmap: Bitmap?) {
                            // 截图完成回调
                            Log.d(TAG, "截图队列中的请求执行完成: $success")
                        }
                    })
                } else {
                    // 直接执行截图
                    requestScreenshot()
                }
            }
        } else {
            Log.w(TAG, "requestScreenshotSafely: 安全检查失败，需要权限")
            notifyPermissionRequired()
        }
    }
    
    /**
     * 检查服务是否正在运行
     */
    private val isServiceRunning: Boolean
        get() {
            val isInstanceValid = instance?.get() == this
            val isMediaProjectionValid = mediaProjection != null
            Log.d(TAG, "isServiceRunning - instance有效: $isInstanceValid, mediaProjection有效: $isMediaProjectionValid")
            return isInstanceValid && isMediaProjectionValid
        }



    // 处理截图队列
    private fun processScreenshotQueue() {
        Log.d(TAG, "processScreenshotQueue: 开始处理截图队列，队列大小: ${screenshotCallbacks.size}")
        
        // 确保只有一个截图操作在进行中
        if (isScreenshotInProgress.get()) {
            Log.d(TAG, "processScreenshotQueue: 已有截图操作正在进行中，跳过此次调用")
            return
        }
        
        // 检查服务状态
        if (!isServiceRunning) {
            Log.w(TAG, "processScreenshotQueue: 服务未正常运行，无法处理截图队列")
            return
        }
        
        // 检查是否有截图请求（队列非空或强制请求标记为true）
        if (screenshotCallbacks.isEmpty() && !isForcedScreenshotRequested) {
            Log.d(TAG, "processScreenshotQueue: 截图队列和强制请求均为空，不执行截图")
            return
        }
        
        // 重置强制请求标记
        if (isForcedScreenshotRequested) {
            isForcedScreenshotRequested = false
        }
        
        // 检查MediaProjection是否可用
        if (mediaProjection == null) {
            Log.w(TAG, "processScreenshotQueue: MediaProjection实例为空")
            // 没有MediaProjection，尝试重建
            recreateMediaProjection()
            
            // 通知所有回调
            val callbacksCopy = ArrayList(screenshotCallbacks)
            screenshotCallbacks.clear()
            callbacksCopy.forEach {
                it.onScreenshotResult(false, null)
            }
            return
        }
        
        Log.d(TAG, "processScreenshotQueue: MediaProjection可用，继续处理截图请求")
        
        if (screenshotCallbacks.isNotEmpty()) {
            Log.d(TAG, "processScreenshotQueue: 从队列中取出回调执行截图")
            // 从队列中取一个回调并执行截图
            val callback = screenshotCallbacks.removeAt(0)
            takeScreenshot(callback)
        } else {
            // 强制请求时执行截图（不使用回调）
            Log.d(TAG, "processScreenshotQueue: 执行强制截图请求")
            takeScreenshot(null)
        }
    }
    
    // 强制截图请求标记
    private var isForcedScreenshotRequested = false
    
    // 请求截图的安全方法，添加防抖动机制
    fun requestScreenshot() {
        // 检查MediaProjection是否有效，如果无效则尝试重建
        if (mediaProjection == null) {
            recreateMediaProjection()
            return
        }
        
        // 将请求添加到队列
        Handler(Looper.getMainLooper()).post { 
            if (isScreenshotInProgress.get()) {
                Log.d(TAG, "Screenshot already in progress")
                return@post
            }
            
            // 设置强制请求标记并处理队列
            isForcedScreenshotRequested = true
            processScreenshotQueue()
        }
    }

    /**
     * 执行截图操作
     */
    private fun takeScreenshot(callback: ScreenshotCallback? = null) {
        // 再次检查服务运行状态
        if (!isServiceRunning) {
            Log.w(TAG, "takeScreenshot: 服务未正常运行，无法执行截图")
            callback?.onScreenshotResult(false, null)
            return
        }
        
        // 检查MediaProjection状态
        if (mediaProjection == null) {
            Log.w(TAG, "takeScreenshot: MediaProjection为空，无法截图")
            callback?.onScreenshotResult(false, null)
            notifyPermissionRequired()
            return
        }

        Log.d(TAG, "takeScreenshot: 开始截图操作")

        // 标记截图正在进行中
        isScreenshotInProgress.set(true)

        // 获取屏幕尺寸
        val metrics = resources.displayMetrics
        val screenWidth = metrics.widthPixels
        val screenHeight = metrics.heightPixels
        val screenDensity = metrics.densityDpi

        Log.d(TAG, "takeScreenshot: 屏幕尺寸 - 宽: $screenWidth, 高: $screenHeight, 密度: $screenDensity")

        try {
            // 创建ImageReader用于捕获屏幕内容
            imageReader = ImageReader.newInstance(
                screenWidth,
                screenHeight,
                IMAGE_READER_FORMAT,
                IMAGE_READER_MAX_IMAGES
            )
            
            // 设置ImageReader的OnImageAvailableListener
            val imageAvailableHandler = Handler(Looper.getMainLooper())
            imageReader?.setOnImageAvailableListener({ reader ->
                try {
                    val image = reader.acquireLatestImage()
                    if (image != null) {
                        Log.d(TAG, "Image acquired successfully")
                        val bitmap = imageToBitmap(image)
                        image.close()
                        
                        if (bitmap != null) {
                            Log.d(TAG, "takeScreenshot: 截图成功，Bitmap尺寸: ${bitmap.width}x${bitmap.height}")
                            
                            // 处理截图结果
                            callback?.onScreenshotResult(true, bitmap)
                            
                            // 将截图数据传递给MainActivity
                            val byteArray = bitmapToByteArray(bitmap)
                            if (byteArray != null) {
                                // 通过广播方式将截图数据发送给MainActivity
                                sendScreenshotToMainActivity(byteArray)
                            } else {
                                Log.e(TAG, "Failed to convert bitmap to valid byte array")
                                callback?.onScreenshotResult(false, bitmap)
                            }
                        } else {
                            Log.e(TAG, "Captured bitmap is null")
                            callback?.onScreenshotResult(false, null)
                        }
                    } else {
                        Log.e(TAG, "Failed to acquire image from ImageReader")
                        callback?.onScreenshotResult(false, null)
                    }
                } catch (e: SecurityException) {
                    Log.e(TAG, "安全权限异常，无法访问屏幕内容: ${e.message}", e)
                    callback?.onScreenshotResult(false, null)
                    notifyPermissionRequired()
                } catch (e: Exception) {
                    Log.e(TAG, "Error capturing screenshot", e)
                    callback?.onScreenshotResult(false, null)
                } finally {
                    // 清理资源
                    stopVirtualDisplay()
                    isScreenshotInProgress.set(false)
                    
                    // 处理下一个截图请求
            Handler(Looper.getMainLooper()).post {
                // 使用安全的方法触发下一个截图请求
                if (screenshotCallbacks.isNotEmpty()) {
                    requestScreenshot()
                }
            }
                }
            }, imageAvailableHandler)
            
            // 添加截图超时机制
            Handler(Looper.getMainLooper()).postDelayed({
                if (isScreenshotInProgress.get()) {
                    Log.e(TAG, "Screenshot operation timed out")
                    callback?.onScreenshotResult(false, null)
                    stopVirtualDisplay()
                    isScreenshotInProgress.set(false)
                    
                    // 处理下一个截图请求
            Handler(Looper.getMainLooper()).post {
                // 使用安全的方法触发下一个截图请求
                if (screenshotCallbacks.isNotEmpty()) {
                    requestScreenshot()
                }
            }
                }
            }, 5000) // 5秒超时
            
            // 检查MediaProjection是否仍然可用
            if (mediaProjection == null) {
                throw IllegalStateException("MediaProjection在创建VirtualDisplay前变为null")
            }
            
            // 创建VirtualDisplay
            virtualDisplay = mediaProjection?.createVirtualDisplay(
                "ScreenshotDisplay",
                screenWidth,
                screenHeight,
                screenDensity,
                VIRTUAL_DISPLAY_FLAGS,
                imageReader?.surface,
                null,
                Handler(Looper.getMainLooper())
            )
            
            // 检查VirtualDisplay是否创建成功
            if (virtualDisplay == null) {
                throw IllegalStateException("VirtualDisplay创建失败")
            }
            
            virtualDisplay?.let {
                Log.d(TAG, "takeScreenshot: VirtualDisplay创建成功")
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "安全权限异常，无法创建VirtualDisplay: ${e.message}", e)
            callback?.onScreenshotResult(false, null)
            isScreenshotInProgress.set(false)
            notifyPermissionRequired()
        } catch (e: IllegalStateException) {
            Log.e(TAG, "takeScreenshot: 状态异常 - ${e.message}", e)
            callback?.onScreenshotResult(false, null)
            isScreenshotInProgress.set(false)
            notifyPermissionRequired()
        } catch (e: Exception) {
            Log.e(TAG, "Error creating virtual display", e)
            callback?.onScreenshotResult(false, null)
            isScreenshotInProgress.set(false)
        }
    }
    
    // 通过广播方式将截图数据发送给MainActivity
    private fun sendScreenshotToMainActivity(byteArray: ByteArray) {
        Log.d(TAG, "Sending screenshot data to MainActivity, size: ${byteArray.size} bytes")
        val intent = Intent("com.joyd.autobot.SCREENSHOT_DATA")
        intent.putExtra("screenshot_data", byteArray)
        intent.setPackage(packageName) // 指定包名，解决UnsafeImplicitIntentLaunch错误
        sendBroadcast(intent)
    }

    // 将Image转换为Bitmap
    private fun imageToBitmap(image: Image): Bitmap? {
        try {
            val planes = image.planes
            val buffer = planes[0].buffer
            val pixelStride = planes[0].pixelStride
            val rowStride = planes[0].rowStride
            val rowPadding = rowStride - pixelStride * image.width
            
            // 检查buffer是否有效
            if (buffer == null || buffer.remaining() <= 0) {
                Log.e(TAG, "Image buffer is invalid or empty")
                return null
            }
            
            // 创建Bitmap
            val bitmap = Bitmap.createBitmap(
                image.width + rowPadding / pixelStride,
                image.height,
                Bitmap.Config.ARGB_8888
            )
            bitmap.copyPixelsFromBuffer(buffer)
            
            // 如果有行填充，裁剪Bitmap
            if (rowPadding > 0) {
                return Bitmap.createBitmap(
                    bitmap,
                    0,
                    0,
                    image.width,
                    image.height
                )
            }
            
            return bitmap
        } catch (e: Exception) {
            Log.e(TAG, "Error converting image to bitmap", e)
            return null
        }
    }

    // 停止VirtualDisplay
    private fun stopVirtualDisplay() {
        try {
            virtualDisplay?.release()
            virtualDisplay = null
        } catch (e: Exception) {
            Log.w(TAG, "Error releasing VirtualDisplay", e)
        }
        
        try {
            imageReader?.close()
            imageReader = null
        } catch (e: Exception) {
            Log.w(TAG, "Error closing ImageReader", e)
        }
    }

    // 释放MediaProjection资源
    private fun releaseMediaProjection() {
        // 首先清理VirtualDisplay和ImageReader资源
        stopVirtualDisplay()
        
        // 只有在没有截图操作进行时才停止MediaProjection
        if (!isScreenshotInProgress.get()) {
            try {
                mediaProjection?.stop()
            } catch (e: Exception) {
                Log.w(TAG, "Error stopping MediaProjection", e)
            } finally {
                mediaProjection = null
            }
        }
    }

    // 将Bitmap转换为字节数组
    private fun bitmapToByteArray(bitmap: Bitmap?): ByteArray? {
        if (bitmap == null) {
            Log.e(TAG, "bitmapToByteArray: bitmap is null")
            return null
        }
        
        try {
            val outputStream = java.io.ByteArrayOutputStream()
            // 使用JPEG格式替代PNG，提高兼容性和转换成功率
            val compressResult = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
            val byteArray = outputStream.toByteArray()
            outputStream.close()
            
            // 验证压缩结果和字节数组是否有效
            if (!compressResult || byteArray.isEmpty()) {
                Log.e(TAG, "bitmapToByteArray: compression failed or result is empty")
                return null
            }
            
            Log.d(TAG, "bitmapToByteArray: conversion successful, size: ${byteArray.size} bytes")
            return byteArray
        } catch (e: Exception) {
            Log.e(TAG, "Error converting bitmap to byte array", e)
            return null
        }
    }

    // 获取当前的MainActivity实例
    // 注意：此方法目前返回null，因为我们已经移除了对MainActivity私有属性的直接访问
    private fun getCurrentMainActivity(): Activity? {
        try {
            // 在现代Android版本中，getRunningTasks已被弃用且不可用
            // 因此此方法简化为直接返回null
            Log.d(TAG, "MainActivity instance is not available through this method")
        } catch (e: Exception) {
            Log.e(TAG, "Error getting MainActivity", e)
        }
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理资源
        releaseMediaProjection()
        // 注意：这里不调用webSocketClient的close方法，因为无法确定其具体类型
        WebSocketForegroundService.clearInstance()
        Log.d(WebSocketForegroundService.TAG, "Service destroyed")
    }

    override fun onBind(intent: Intent?): IBinder? {
        // 不支持绑定
        return null
    }
}